package com.clip.action;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import sun.misc.BASE64Encoder;

import com.clip.action.util.CookieAttributeKey;
import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserRegApply;
import com.clip.entity.UserRegInvites;
import com.clip.entity.virtual.EventForView;
import com.clip.service.ContactService;
import com.clip.service.NoticeItemService;
import com.clip.service.UserEmailService;
import com.clip.service.UserRegApplyService;
import com.clip.service.UserRegInvitesService;
import com.clip.service.UserService;
import com.clip.service.UsermobileinfoService;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.clip.util.mobile.HttpResponse;
import com.clip.util.mobile.HttpResponseXmlAnalyze;
import com.clip.util.mobile.MobileEnv;
import com.clip.util.mobile.MobileHttpSender;
import com.clip.util.mobile.MobileMsgPattern;
import com.clip.util.verifycode.VerifyCode;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope("prototype")
public class UserAction extends ActionSupport{
	
	private static final long serialVersionUID = 7744823390283253126L;
	
	private final int INVITEFRIENDNOTICE=1;
	private final int ALERTMETHODNOTICE=2;
	
	private final String emailRegex="^([\\w\\-\\.]+)@((\\[([0-9]{1,3}\\.){3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$";
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserEmailService userEmailService;
	@Autowired
	private UserRegInvitesService userRegInvitesService;
	@Autowired
	private UserRegApplyService userRegApplyService;
	@Autowired
	private UsermobileinfoService usermobileinfoService;
	@Autowired
	private NoticeItemService noticeItemService;
	@Autowired
	private ContactService contactService;
	private int uid;
	private String emailInput;
	private String pwdInput;
	private String pwdInput2;
	private String nameInput;
	private String vcodeInput;
	private String activate;
	private String mobilenum;
	private String codenum;
	private int usertype;
	private int currentpage;
	/**
	 * oldPwdInput 原密码
	 * pwdInput 新密码
	 */
	public void modifyPwd(){
		String result="{result:'修改失败',flag:0}";
		HttpServletRequest request=ServletActionContext.getRequest();
		String oldPwdInput=request.getParameter("oldPwdInput");
		if(ToolsUtils.searchEmpty(oldPwdInput,pwdInput,pwdInput2).size()<=0){
			User user=(User) request.getSession().getAttribute(SessionAttributeKey.USER);
			user=userService.getUserByEmail(user.getEmail());
			if(user!=null){
				if(user.getPwd().equals(ToolsUtils.getStringForMD5(oldPwdInput))&&pwdInput.equals(pwdInput2)){
					user.setPwd(ToolsUtils.getStringForMD5(this.pwdInput));
					if(userService.updateUser(user)!=null){
						result="{result:'修改成功',flag:1}";
					}
				}else{
					result="{result:'原密码错误,修改失败.',flag:0}";
				}
			}
		}
		Struts2Utils.renderText(result);
	}
	//判断密码
	public void checkPwd(){
		String result="{result:'密码错误',flag:0}";
		String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}";
		if(ToolsUtils.searchEmpty(pwdInput).size()<=0&&pwdInput.matches(pwdRegex)){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User user=(User) session.getAttribute(SessionAttributeKey.USER);
			user=userService.getUserByEmail(user.getEmail());
			if(user!=null){
				if(user.getPwd().equals(ToolsUtils.getStringForMD5(pwdInput))){
					result="{result:'密码正确',flag:1}";
				}
			}else{
				result="{result:'您需要登录',flag:0}";
			}
		}
		Struts2Utils.renderText(result);
	}
	//判断用户是否登录
	public void checkExistUser(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		User user = (User)session.getAttribute(SessionAttributeKey.USER);
		long systime=new Date().getTime();
		String result=null;
		if(user!= null){
			boolean flag=usermobileinfoService.isHasBindableMobile(user.getId());
			int temp=flag?1:0;
			boolean isExist=this.noticeItemService.findNotice(this.INVITEFRIENDNOTICE,user);
			String url=(String) session.getAttribute(SessionAttributeKey.USERLOGO_BIG);
			String surl=(String) session.getAttribute(SessionAttributeKey.USERLOGO_SMALL);
			if(url==null||surl==null){
				this.userService.checkUserLogo(false, session);
				url=(String) session.getAttribute(SessionAttributeKey.USERLOGO_BIG);
				surl=(String) session.getAttribute(SessionAttributeKey.USERLOGO_SMALL);
			}
			StringBuffer buffer=new StringBuffer();
			buffer.append("{loginflag:1,email:'");
			buffer.append(user.getEmail());
			buffer.append("',url:'");
			buffer.append(url);
			buffer.append("',surl:'");
			buffer.append(surl);
			buffer.append("',name:'");
			buffer.append(user.getName());
			buffer.append("',systime:'");
			buffer.append(systime);
			buffer.append("',mobilenotice:");
			buffer.append(temp);
			buffer.append(",usertype:");
			buffer.append(user.getUsertype());
			buffer.append(",uid:");
			buffer.append(user.getId());
			if(isExist){
				buffer.append("}");
			}else{
				buffer.append(",invitefriendnotice:0}");
			}
			result=buffer.toString();
		}else{
			HttpServletRequest request=Struts2Utils.getRequest();
			String url=request.getHeader("referer");
			if(url.indexOf("index.html")<0){
				session.setAttribute(SessionAttributeKey.VISITURL,url);
			}
			this.userService.checkUserLogo(false, session);
			String logourl=(String) session.getAttribute(SessionAttributeKey.USERLOGO_SMALL);
			result="{loginflag:0,systime:"+systime+"}";
		}
		Struts2Utils.renderText(result);
	}
	/*
	 * 用户登录
	 */
	public void login(){
		String result="{result:'您的密码或账号错误,登录失败！',flag:0}";
		if(ToolsUtils.searchEmpty(emailInput,pwdInput,activate).size()<=0){
			User user = userService.getUserByEmail(emailInput);
			if(user!=null&&ToolsUtils.getStringForMD5(pwdInput).equals(user.getPwd())){
				if(user.getStatus()==1){
					HttpSession session = ServletActionContext.getRequest().getSession();
					session.setAttribute(SessionAttributeKey.USER, user);
					this.userService.checkUserLogo(false,session);
					BASE64Encoder e = new BASE64Encoder();
					String cookieInfo;
					if(Boolean.valueOf(activate)){
						cookieInfo = e.encode((user.getEmail()+",auto").getBytes());
					}else{
						cookieInfo = e.encode((user.getEmail()+",no").getBytes());
					}
					Cookie cookie = new Cookie("clip24user", cookieInfo);
					cookie.setMaxAge(7*24*60*60);
					cookie.setPath("/");
					ServletActionContext.getResponse().addCookie(cookie);
					String visiturl=(String) session.getAttribute(SessionAttributeKey.VISITURL);
					if(visiturl!=null&&visiturl.length()>0){
						session.removeAttribute(SessionAttributeKey.VISITURL);
						result="{result:'登录成功！',flag:1,visiturl:'"+visiturl+"'}";
					}else
						result="{result:'登录成功！',flag:1}";
				}else{
					result="{needactive:1,flag:1}";
				}
			}
		}
		Struts2Utils.renderHtml(result);
	}
	/*
	 * 用户退出
	 */
	public void logout(){
		HttpServletRequest request= ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		User user = (User)request.getSession().getAttribute(SessionAttributeKey.USER);
		Cookie[] cookies=request.getCookies(); 
		if(cookies!=null&&user!=null){
			for(int i=0;i<cookies.length;i++){
				if(cookies[i].getName().equals(CookieAttributeKey.COOKIENAME)){
					Cookie removeCookie = new Cookie(CookieAttributeKey.COOKIENAME,new BASE64Encoder().encode((user.getEmail()+",no").getBytes()));
					removeCookie.setPath("/");
					response.addCookie(removeCookie);
				}
			}
		}
		request.getSession().removeAttribute(SessionAttributeKey.USER);
	}
	/*
	 * 重置密码
	 */
	public void resetPwd(){
		String result="";
		String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}";
		//不为空\密码\正确\合法
		if(ToolsUtils.searchEmpty(pwdInput,pwdInput2).size()<=0&&pwdInput.matches(pwdRegex)&&pwdInput.equals(pwdInput2)){
			result=userService.pwdReset(activate, pwdInput);
		}
		Struts2Utils.renderHtml(result);
	}
	/*
	 * 密码重置授权
	 */
	public void resetPwdAuthorize(){
		String result="{result:'您的链接无效！',flag:'0'}";
		if(ToolsUtils.searchEmpty(activate).size()<=0){
			result=userService.pwdResetAuthorize(activate);
		}
		Struts2Utils.renderHtml(result);
	}
	/*
	 * 提交'密码找回'信息
	 */
	public void forgetPwd(){
		String result="";
		boolean flag = false;
		String verifyCode=(String)ServletActionContext.getRequest().getSession().getAttribute("verifyCode");
		
		if(emailInput==null||!emailInput.matches(emailRegex)){
			result="{result:'邮箱地址不正确',flag:0}";
			flag = true;
		}
		if(nameInput==null){
			result="{result:'请输入姓名',flag:0}";
			flag = true;
		}
		if(vcodeInput==null){
			result="{result:'验证码输入错误',flag:0}";
			flag = true;
		}
		if(!flag){
			vcodeInput=vcodeInput.toLowerCase();
			verifyCode=verifyCode.toLowerCase();
			if(vcodeInput.equals(verifyCode)){
				result = userService.forgetPwd(emailInput, nameInput);
			}else{
				result="{result:'验证码输入错误',flag:0}";
			}
		}
		Struts2Utils.renderHtml(result);
	}
	/*
	 * 激活用户
	 */
	public void activite(){
		String result="{result:'无效的链接',flag:0}";
		if(activate!=null&&activate!=""){
			result = userService.activite(activate);
		}
		Struts2Utils.renderHtml(result);
	}
	
	public void resendActiveEmail(){
		this.userService.resendActiveEmail(this.emailInput,this.pwdInput);
		Struts2Utils.renderHtml("{flag:1}");
	}
	/*
	 * 注册用户
	 */
	public void register(){
		String json="{result:'注册失败',flag:0}";
		int flag = 0;
		String msg = "";
		HttpServletRequest request = ToolsUtils.getRequest();
		String verifyCode= (String)request.getSession().getAttribute("verifyCode");
		String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}$";
		if(emailInput==null){
			flag = -1;
			msg = "输入邮箱地址";
		}else if(pwdInput==null){
			flag = -2;
			msg = "输入密码";
		}else if(pwdInput2==null){
			flag = -3;
			msg = "输入密码不一致";
		}else if(nameInput==null){
			flag = -4;
			msg = "输入姓名";
		}else if(vcodeInput==null){
			flag = -5;
			msg = "输入验证码";
		}
		if(flag>=0){
			vcodeInput=vcodeInput.toLowerCase();
			verifyCode=verifyCode.toLowerCase();
			if(vcodeInput.equals(verifyCode)&&emailInput.matches(emailRegex)&&pwdInput.matches(pwdRegex)&&pwdInput.equals(pwdInput2)){
				json = userService.register(emailInput,ToolsUtils.htmlEnCode(nameInput),pwdInput);
			}
		}else{
			json="{flag:"+flag+",'result':'"+msg+"'}";
		}
		Struts2Utils.renderHtml(json);
	}
	/**
	 * 接受邀请 时用户注册
	 */
	/*
	public void registerInvite(){
		String json="{result:'注册失败',flag:0}";
		int flag = 0;
		String msg = "";
		HttpServletRequest request = ToolsUtils.getRequest();
		String verifyCode= (String)request.getSession().getAttribute("verifyCode");
		String emailRegex="^[a-z0-9_\\.]+@([a-z0-9][a-z0-9]+\\.){1,4}[a-z]{2,3}";
		String pwdRegex="^[a-zA-Z0-9][a-zA-Z0-9_-]{5,19}";
		String nameRegex="^[A-Za-z0-9\u4e00-\u9fa5]{2,20}";
		String vcodeRegex="[A-Za-z0-9]{4,4}";
		if(activate==null){
			flag = -6;
			msg = "你没有被邀请";
		}else if(emailInput==null){
			flag = -1;
			msg = "输入邮箱地址";
		}else if(pwdInput==null){
			flag = -2;
			msg = "输入密码";
		}else if(pwdInput2==null){
			flag = -3;
			msg = "输入密码不一致";
		}else if(nameInput==null){
			flag = -4;
			msg = "输入姓名";
		}else if(vcodeInput==null){
			flag = -5;
			msg = "输入验证码";
		}
		if(flag>=0){
			if(emailInput.matches(emailRegex)&&pwdInput.matches(pwdRegex)&&nameInput.matches(nameRegex)&&vcodeInput.matches(vcodeRegex)&&pwdInput.equals(pwdInput2)){
				vcodeInput=vcodeInput.toLowerCase();
				verifyCode=verifyCode.toLowerCase();
				if(vcodeInput.equals(verifyCode)){
					json="{flag:0,'result':'此邀请无效'}";
					UserRegInvites uri = userRegInvitesService.findUserRegInvitesByCode(activate);
					if(uri!=null){
						if(uri.getStatus()==0){
							UserRegApply userRegApply = userRegApplyService.findUserRegApplyById(uri.getReguid());
							if(userRegApply!=null){
								User user = new User();
								user.setBirth(userRegApply.getBirth());
								user.setBlog(userRegApply.getBlog());
								user.setEdu(userRegApply.getEdu());
								user.setEmail(userRegApply.getEmail());
								user.setJob(userRegApply.getJob());
								user.setLiving(userRegApply.getLiving());
								user.setName(userRegApply.getName());
								user.setPwd(ToolsUtils.getStringForMD5(pwdInput));
								user.setSex(userRegApply.getSex());
								user.setStatus(1);
								json = userService.register1(user,uri);
							}
						}
					}
//					json = userService.register(emailInput,nameInput,pwdInput);
				}else{
					json="{flag:0,result:'验证码错误'}";
				}
			}
		}else{
			json="{flag:"+flag+",result:'"+msg+"'}";
		}
		Struts2Utils.renderText(json);
	}*/
	/*
	 * 验证"验证码"
	 */
	public void checkYzm(){
		String result="0";
		String verifyCode=(String)ServletActionContext.getRequest().getSession().getAttribute("verifyCode");
		if(vcodeInput!=null&&verifyCode!=null&&verifyCode!=""&&vcodeInput!=""){
			vcodeInput=vcodeInput.toLowerCase();
			verifyCode=verifyCode.toLowerCase();
			if(vcodeInput.equals(verifyCode)){
				result="1";
			}
		}
		Struts2Utils.renderHtml(result);
	}
	/*
	 * 验证Email 是否存在
	 */
	public void checkUser(){
		String result="0";
		
//		User user = userService.getUserByEmail(emailInput);
		UserEmail userEmail = userEmailService.getUserEmailByEmail(emailInput);
		
		if(userEmail==null)
			result="1";
		else
			result="0";
		
		Struts2Utils.renderText(result);
	}
	
	public void searchUserByName(){
		HttpServletRequest request= ServletActionContext.getRequest();
		User crtuser = (User)request.getSession().getAttribute(SessionAttributeKey.USER);
		String nameRegex="^[A-Za-z0-9\u4e00-\u9fa5]{1,20}";
		if(nameInput.matches(nameRegex)){
			List<User> users=this.userService.searchUserByName(nameInput,crtuser,this.usertype);
			if(this.usertype==1){
				Map<String, Map> returnMap=new LinkedHashMap<String, Map>();
				for (User user : users) {
					Map<String,Object> temp2=new HashMap<String,Object>();
					temp2.put("name", user.getName());
					temp2.put("email", user.getEmail());
					//temp2.put("birth", ""+user.getBirth());
					//temp2.put("sex", user.getSex()==null?"":user.getSex());
					//temp2.put("living", user.getLiving()==null?"":user.getLiving());
					boolean flag=this.userService.checkHasRelationship(crtuser.getId(),user.getId());
					String biglogo=(String) UserService.getUserLogoByUid(user.getId()).get(0);
					temp2.put("ulogo",ToolsUtils.xmlCDATA(biglogo));
					temp2.put("isfriend", flag);
					returnMap.put("User uid="+user.getId(), temp2);
				}
				Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
			}else if(this.usertype==2){
				Map<String, Map> returnMap=new LinkedHashMap<String, Map>();
				for (User user : users) {
					Map<String,Object> temp2=new HashMap<String,Object>();
					temp2.put("name", user.getName());
					temp2.put("job", user.getJob());
					boolean isSubcribe=this.userService.checkIsSubscribed(crtuser.getId(),user.getId());
					String biglogo=(String) UserService.getUserLogoByUid(user.getId()).get(0);
					temp2.put("ulogo",ToolsUtils.xmlCDATA(biglogo));
					temp2.put("isSubcribe", isSubcribe);
					temp2.put("subscribedcount", this.contactService.countAllSubscribedUsers(user.getId()));
					returnMap.put("User uid="+user.getId(), temp2);
				}
				Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
			}
		}else{
			Struts2Utils.renderText("");
		}
	}
	
	public void sendVerCode(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		if(user==null){
			Struts2Utils.renderText("{flag:0,result:'对不起，您可能还未激活账户或未登录网站。'}");
			return;
		}else{
			boolean flag=this.usermobileinfoService.isMobileBindable(mobilenum);
			if(flag){
				Struts2Utils.renderText("{flag:0,result:'对不起，您的账户已绑定手机。'}");
				return;
			}else{
				Map vermap=(Map) session.getAttribute(SessionAttributeKey.VERCODE);
				
				if(vermap==null){
					vermap=new HashMap();
					Date date=new Date();
					vermap.put("lasttime", date.getTime());
					String validatenum=VerifyCode.getValidateNumber();
					vermap.put("mobilenum", this.mobilenum);
					vermap.put("code", validatenum);
					session.setAttribute(SessionAttributeKey.VERCODE,vermap);
					sendMobileMsg(user.getName(),validatenum);
				}else{
					Calendar now=Calendar.getInstance();
					Calendar temp=(Calendar) now.clone();
					Long lasttime=(Long) vermap.get("lasttime");
					temp.setTimeInMillis(lasttime);
					temp.add(Calendar.MINUTE, 1);
					if(temp.getTimeInMillis()>now.getTimeInMillis()){
						Struts2Utils.renderText("{flag:0,result:'对不起，请勿频繁请求手机验证码，每隔2分钟请求一次。'}");
						return;
					}else{
						String validatenum=VerifyCode.getValidateNumber();
						vermap.put("lasttime", now.getTimeInMillis());
						vermap.put("mobilenum", this.mobilenum);
						vermap.put("code", validatenum);
						session.setAttribute(SessionAttributeKey.VERCODE,vermap);
						sendMobileMsg(user.getName(),validatenum);
					}
					
				}
			}
		}
	}
	
	public void verifyCode(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		if(user==null){
			Struts2Utils.renderText("{flag:0,result:'对不起，您可能还未激活账号或未登录网站。'}");
			return;
		}else{
			boolean flag=this.usermobileinfoService.isMobileBindable(mobilenum);
			if(flag){
				Struts2Utils.renderText("{flag:0,result:'对不起，该手机号已被使用，一个手机号只能绑定在一个账户上。'}");
				return;
			}else{
				if(this.usermobileinfoService.isHasBindableMobile(user.getId())){
					Struts2Utils.renderText("{flag:0,result:'对不起，您的账户上已经绑定了手机。'}");
					return;
				}
				Map vermap=(Map) session.getAttribute(SessionAttributeKey.VERCODE);
				if(vermap==null){
					Struts2Utils.renderText("{flag:0,result:'对不起，您还未请求新的验证码发送给您的手机。'}");
					return;
				}else{
					Calendar now=Calendar.getInstance();
					String code=(String) vermap.get("code");
					String mobilenum=(String) vermap.get("mobilenum");
					if(code.equals(this.codenum)){
						Long lasttime=(Long) vermap.get("lasttime");
						Calendar lastsend=Calendar.getInstance();
						lastsend.setTimeInMillis(lasttime);
						lastsend.add(Calendar.MINUTE, 10);
						if(lastsend.getTimeInMillis()>=now.getTimeInMillis()){
							this.usermobileinfoService.bindMobileWithUser(mobilenum,user);
							Struts2Utils.renderText("{flag:1,result:'验证成功，您的手机号已绑定在您的账号上。'}");
						}else{
							session.removeAttribute(SessionAttributeKey.VERCODE);
							Struts2Utils.renderText("{flag:0,result:'对不起，您输入的验证码超时，请在10分钟内验证。'}");
						}
					}else{
						Struts2Utils.renderText("{flag:0,result:'对不起，请输入正确的验证码或重新发送新的验证码给您的手机。'}");
					}
				}
			}
		}
	}
	
	public void sendVerCodeAndReset(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		if(user==null){
			Struts2Utils.renderText("{flag:0,result:'对不起，您可能还未激活账号或未登录网站。'}");
			return;
		}else{
			boolean flag=this.usermobileinfoService.isMobileBindable(mobilenum);
			if(flag){
				Struts2Utils.renderText("{flag:0,result:'对不起，该手机号已被使用，一个手机号只能绑定在一个账户上。'}");
				return;
			}else{
				this.usermobileinfoService.resetBindableMobile(user.getId());
				Map vermap=(Map) session.getAttribute(SessionAttributeKey.VERCODE);
				if(vermap==null){
					vermap=new HashMap();
					Date date=new Date();
					vermap.put("lasttime", date.getTime());
					String validatenum=VerifyCode.getValidateNumber();
					vermap.put("mobilenum", this.mobilenum);
					vermap.put("code", validatenum);
					session.setAttribute(SessionAttributeKey.VERCODE,vermap);
					sendMobileMsg(user.getName(),validatenum);
					return;
				}else{
					Calendar now=Calendar.getInstance();
					Calendar temp=(Calendar) now.clone();
					Long lasttime=(Long) vermap.get("lasttime");
					temp.setTimeInMillis(lasttime);
					temp.add(Calendar.MINUTE, 1);
					if(temp.getTimeInMillis()>now.getTimeInMillis()){
						Struts2Utils.renderText("{flag:0,result:'对不起，请勿频繁请求手机验证码，每隔2分钟请求一次。'}");
						return;
					}else{
						vermap.put("lasttime", now.getTimeInMillis());
						vermap.put("mobilenum", this.mobilenum);
						session.setAttribute(SessionAttributeKey.VERCODE,vermap);
						String validatenum=VerifyCode.getValidateNumber();
						sendMobileMsg(user.getName(),validatenum);
					}
				}
			}
		}
	}
	
	public void isHasBindableMobile(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		boolean isExist=this.noticeItemService.findNotice(this.ALERTMETHODNOTICE,user);
		
		boolean flag=this.usermobileinfoService.isHasBindableMobile(user.getId());
		int temp=flag?1:0;
		int temp2=isExist?1:0;
		Struts2Utils.renderText("{flag:"+temp+",alertmethodnotice:"+temp2+"}");
	}
	
	private void sendMobileMsg(String name,String validatenum){
		String content=MobileHttpSender.sendMobileMsg(this.mobilenum, MobileMsgPattern.getMobileBundlingMsg(name, validatenum));
		int result=HttpResponseXmlAnalyze.getSendResult(content);
		switch (result) {
			case 0:
				Struts2Utils.renderText("{flag:1,result:'发送成功，验证码已以短消息形式发送至您的手机。（验证码10分钟后过期）'}");
				break;
			case 1:
				Struts2Utils.renderText("{flag:0,result:'发送失败，您的手机号码格式不正确。'}");
				break;
			case 11:
				Struts2Utils.renderText("{flag:0,result:'发送失败，您的短信内容包含非法字词。'}");
				break;
			default:
				Struts2Utils.renderText("{flag:0,result:'发送失败，系统发生错误。'}");
				break;
		}
	}
	
	public void cancelInviteFriendNotice(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		this.noticeItemService.createObject(user,this.INVITEFRIENDNOTICE,"具有MSN导入、邮箱邀请、好友搜索功能");
		Struts2Utils.renderText("{flag:1}");
	}
	
	
	public void cancelAlertMethodNotice(){
		HttpSession session=Struts2Utils.getSession();
		User user=(User) session.getAttribute(SessionAttributeKey.USER);
		this.noticeItemService.createObject(user,this.ALERTMETHODNOTICE,"您可以设置提醒时间，来记住重要的日子哦");
		Struts2Utils.renderText("{flag:1}");
	}
	
	public void loadUserBaseInfo(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		User visitUser=this.userService.getUserById(uid);
		Map returnMap=new LinkedHashMap();
		Map smallmap=new HashMap();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy.MM.dd");
		if(visitUser.getUsertype()==1){
			if(currentUser.getId()==visitUser.getId()){
				smallmap.put("usertype",visitUser.getUsertype());
				smallmap.put("isuserself", true);
				smallmap.put("realname", currentUser.getName());
				smallmap.put("email", currentUser.getEmail());
				smallmap.put("mobile", usermobileinfoService.getBindableMobile(currentUser.getId()));
				if(currentUser.getBirth()!=null&&currentUser.getBirth()>0l){
					Date date=new Date();
					date.setTime(currentUser.getBirth());
					smallmap.put("birth", dateFormat.format(date));
				}else
					smallmap.put("birth","");
				List templist=this.userService.getUserLogoByUid(currentUser.getId());
				smallmap.put("userlogo",templist.get(0));
				smallmap.put("smalluserlogo",templist.get(1));
				returnMap.put("user uid="+0,smallmap);
			}else{
				smallmap.put("isuserself", false);
				smallmap.put("name",this.contactService.getUserName(currentUser.getId(),visitUser.getId()));
				int usertype=currentUser.getUsertype();
				boolean isfriend=this.contactService.judgeRelation(visitUser, currentUser);
				boolean hasinvite=false;
				if(usertype==2){
					smallmap.put("realname", visitUser.getName());
					smallmap.put("email", visitUser.getEmail());
					smallmap.put("mobile", usermobileinfoService.getBindableMobile(visitUser.getId()));
					if(visitUser.getBirth()!=null&&visitUser.getBirth()>0l){
						Date date=new Date();
						date.setTime(visitUser.getBirth());
						smallmap.put("birth", dateFormat.format(date));
					}else
						smallmap.put("birth","");
				}else{
					
					if(!isfriend){
						hasinvite=this.contactService.judgeHasInvited(visitUser, currentUser);
					}else{
						smallmap.put("realname", visitUser.getName());
						smallmap.put("email", visitUser.getEmail());
						smallmap.put("mobile", usermobileinfoService.getBindableMobile(visitUser.getId()));
						if(visitUser.getBirth()!=null&&visitUser.getBirth()>0l){
							Date date=new Date();
							date.setTime(visitUser.getBirth());
							smallmap.put("birth", dateFormat.format(date));
						}else
							smallmap.put("birth","");
					}
				}
				
				smallmap.put("usertype",visitUser.getUsertype());
				
				smallmap.put("relation", isfriend);
				smallmap.put("hasinvite", hasinvite);
				List templist=this.userService.getUserLogoByUid(visitUser.getId());
				smallmap.put("userlogo",templist.get(0));
				smallmap.put("smalluserlogo",templist.get(1));
				returnMap.put("user uid="+visitUser.getId(),smallmap);
			}
		}else{
			smallmap.put("usertype",visitUser.getUsertype());
			smallmap.put("name", visitUser.getName());
			smallmap.put("blog", visitUser.getBlog());
			smallmap.put("bgurl", visitUser.getBgurl());
			smallmap.put("userstatus", visitUser.getUserstatus());
			List templist=this.userService.getUserLogoByUid(visitUser.getId());
			smallmap.put("userlogo",templist.get(0));
			smallmap.put("smalluserlogo",templist.get(1));
			smallmap.put("issubsribed", this.userService.checkIsSubscribed(currentUser.getId(),visitUser.getId()));
			smallmap.put("subscribedcount", this.contactService.countAllSubscribedUsers(visitUser.getId()));
			returnMap.put("user uid="+visitUser.getId(),smallmap);
		}
		Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
	}
	
	public void checkHasContacts(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		long counthas=this.contactService.getUserContactTotalCount(currentUser,1);
		if(counthas>0l){
			Struts2Utils.renderText("{flag:1}");
		}else{
			Struts2Utils.renderText("{flag:0}");
		}
	}
	
	public void loadUserSubscribed(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		long count=this.userService.countUserSubscribed(currentUser.getId());
		List list=this.userService.getUserSubscribed(currentUser.getId(),this.currentpage);
		BigDecimal br = new BigDecimal(count).divide(new BigDecimal(UserService.USERSUBSCRIBELENGTH),BigDecimal.ROUND_UP);
		Integer pageCount = (br.doubleValue()<1&&br.doubleValue()>=0 ? 1 : br.intValue());
		Map returnMap=new LinkedHashMap();
		for (Object object : list) {
			Map smallmap=new HashMap();
			User user=(User) object;
			List headlist=this.userService.getUserLogoByUid(user.getId());
			smallmap.put("name",user.getName());
			smallmap.put("smalllogo", ToolsUtils.xmlCDATA(headlist.get(1)));
			smallmap.put("subscribedcount", this.contactService.countAllSubscribedUsers(user.getId()));
			returnMap.put("User id="+user.getId(), smallmap);
		}
		returnMap.put("pagecount", pageCount);
		returnMap.put("currentpage", currentpage);
		Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
	}
	
	public void loadUserAllSubscribed(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		List list=this.userService.getUserAllSubscribed(currentUser.getId());
		Map returnMap=new LinkedHashMap();
		for (Object object : list) {
			Map smallmap=new HashMap();
			User user=(User) object;
			smallmap.put("name",user.getName());
			returnMap.put("User id="+user.getId(), smallmap);
		}
		Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
	}
	
	public void loadAllsubscribed(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		long count=this.userService.countAllsubscribes(currentUser.getId());
		List list=this.userService.getAllsubscribes(this.currentpage);
		BigDecimal br = new BigDecimal(count).divide(new BigDecimal(UserService.USERUNSUBSCRIBELENGTH),BigDecimal.ROUND_UP);
		Integer pageCount = (br.doubleValue()<1&&br.doubleValue()>=0 ? 1 : br.intValue());
		Map returnMap=new LinkedHashMap();
		for (Object object : list) {
			Map smallmap=new HashMap();
			User user=(User) object;
			List headlist=this.userService.getUserLogoByUid(user.getId());
			smallmap.put("name",user.getName());
			smallmap.put("desc", user.getJob());
			smallmap.put("biglogo",ToolsUtils.xmlCDATA(headlist.get(0)));
			smallmap.put("issubscribed", this.userService.checkIsSubscribed(currentUser.getId(), user.getId()));
			smallmap.put("subscribedcount", this.contactService.countAllSubscribedUsers(user.getId()));
			returnMap.put("User id="+user.getId(), smallmap);
		}
		returnMap.put("pagecount", pageCount);
		returnMap.put("currentpage", currentpage);
		Struts2Utils.renderXml(ToolsUtils.getDOM(returnMap));
	}
	
	public String getEmailInput() {
		return emailInput;
	}
	public void setEmailInput(String emailInput) {
		this.emailInput = emailInput;
	}
	public String getPwdInput() {
		return pwdInput;
	}
	public void setPwdInput(String pwdInput) {
		this.pwdInput = pwdInput;
	}
	public String getPwdInput2() {
		return pwdInput2;
	}
	public void setPwdInput2(String pwdInput2) {
		this.pwdInput2 = pwdInput2;
	}
	public String getNameInput() {
		return nameInput;
	}

	public void setNameInput(String nameInput) {
		this.nameInput = nameInput;
	}

	public String getVcodeInput() {
		return vcodeInput;
	}

	public void setVcodeInput(String vcodeInput) {
		this.vcodeInput = vcodeInput;
	}

	public String getActivate() {
		return activate;
	}

	public void setActivate(String activate) {
		this.activate = activate;
	}
	public String getMobilenum() {
		return mobilenum;
	}
	public void setMobilenum(String mobilenum) {
		this.mobilenum = mobilenum;
	}
	public String getCodenum() {
		return codenum;
	}
	public void setCodenum(String codenum) {
		this.codenum = codenum;
	}
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public int getUsertype() {
		return usertype;
	}
	public void setUsertype(int usertype) {
		this.usertype = usertype;
	}
	public int getCurrentpage() {
		return currentpage;
	}
	public void setCurrentpage(int currentpage) {
		this.currentpage = currentpage;
	}
	
	
}
